package com.woniuxy.rms.realm;

import com.woniuxy.rms.dao.AdminMapper;
import com.woniuxy.rms.dao.RolesMapper;
import com.woniuxy.rms.pojo.Admins;
import com.woniuxy.rms.pojo.Roles;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * Auther: ChenGang  <br/>
 * Date: 2020/3/23 0023:下午 8:37  <br/>
 * Description:自定义域
 */
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    AdminMapper adminMapper;

    @Autowired
    RolesMapper rolesMapper;
  /**
   * Description : 授权  <br/>
   * ChangeLog : 1. 创建 (2020/3/23 0023 下午 8:37 [ChenGang]);
   * @param principal
   * @return org.apache.shiro.authz.AuthorizationInfo
  */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        //获取成功认证的主体
        Admins admins = (Admins) principal.getPrimaryPrincipal();
        //根据角色的id查询权限
        List<String> perms = rolesMapper.findPermissionByRoleId(admins.getRoleId());
        //查询角色
        Roles roles = rolesMapper.selectByPrimaryKey(admins.getRoleId());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermissions(perms);
        info.addRole(roles.getRole());
        return info;
    }

    /**
     * Description : 认证  <br/>
     * ChangeLog : 1. 创建 (2020/3/23 0023 下午 8:38 [ChenGang]);
     * @param token
     * @return org.apache.shiro.authc.AuthenticationInfo
    */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取到前端传过来的用户名
        String account = (String) token.getPrincipal();
        //通过用户名查找用户信息
        Admins admins = adminMapper.findByAccount(account);
        if (admins == null){
            throw new UnknownAccountException("该用户不存在！");
        }
        //认证
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(admins,admins.getPassWord(),super.getName());
        //设置盐值,账户作为盐
        info.setCredentialsSalt(ByteSource.Util.bytes(account));
        return info;
    }
}